﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;

namespace FYPHP
{
    public partial class AdvertisementManage : System.Web.UI.Page
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["fyphp"].ConnectionString);

        protected void Page_Load(object sender, EventArgs e)
        {
            SqlCommand cmdAds;
            SqlDataReader dtrAds;
            conn.Open();

            cmdAds = new SqlCommand("SELECT * FROM Advertisements WHERE a_status='pending'", conn);
            dtrAds = cmdAds.ExecuteReader();

            ItemList.DataSource = dtrAds;
            ItemList.DataBind();
            dtrAds.Close();

            cmdAds = new SqlCommand("SELECT * FROM Advertisements WHERE a_status='published'", conn);
            dtrAds = cmdAds.ExecuteReader();

            ItemList2.DataSource = dtrAds;
            ItemList2.DataBind();
            dtrAds.Close();

            conn.Close();
        }

        protected void ItemList_ItemCommand(Object Sender, RepeaterCommandEventArgs e)
        {
            int aid = Convert.ToInt32(e.CommandArgument.ToString());
            
            if (e.CommandName == "ChangeAds")
            {
                SqlCommand cmdIn;
                conn.Open();
                
                cmdIn = new SqlCommand("UPDATE Advertisements SET a_status='published' WHERE a_id='" + aid + "'", conn);
                cmdIn.ExecuteNonQuery();

                conn.Close();
                MessageBox("Update Successfully.");
                Redirect("AdsManage.aspx");
            }
            else if (e.CommandName == "EditAds")
            {
                Response.Redirect("AdsEdit.aspx?aid="+Convert.ToString(aid));
            }
            else if (e.CommandName == "RemoveAds")
            {
                SqlCommand cmdIn;
                conn.Open();

                cmdIn = new SqlCommand("UPDATE Advertisements SET a_status='removed' WHERE a_id=@id", conn);
                cmdIn.Parameters.AddWithValue("@id", aid);
                cmdIn.ExecuteNonQuery();

                conn.Close();
                MessageBox("Update Successfully.");
                Redirect("AdsManage.aspx");
            }
        }

        private void MessageBox(string msg)
        {
            Label lbl = new Label();
            lbl.Text = "<script language='javascript'>" + Environment.NewLine + "window.alert('" + msg + "')</script>";
            Page.Controls.Add(lbl);
        }

        private void Redirect(string msg)
        {
            Label lbl = new Label();
            lbl.Text = "<script language=\"javascript\">window.location='" + msg + "';</script>";
            Page.Controls.Add(lbl);
        }
    }
}